package com.spboot.tx.controller;


import com.alibaba.fastjson.JSONObject;

import com.jntoo.db.DB;
import com.jntoo.db.utils.StringUtil;
import com.spboot.tx.pojo.Siliao;
import com.spboot.tx.pojo.Xiaoxi;
import com.spboot.tx.utils.Info;
import com.spboot.tx.utils.JsonResult;
import com.spboot.tx.utils.ResponseData;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/chat")
public class ChatController {

    @RequestMapping("/check")
    public synchronized ResponseData<Object> check(@RequestBody Map<String, Object> req)
    {
        JSONObject jsonObject = new JSONObject(req);
        String sid = jsonObject.getString("sid");
        String rid = jsonObject.getString("rid");

        Siliao siliao = DB.name(Siliao.class).where("(faxinren = '"+sid+"' AND shouxinren='"+rid+"') OR (faxinren = '"+rid+"' AND shouxinren='"+sid+"')").find();
        if(siliao == null){
            siliao = new Siliao();
            siliao.setFaxinren(sid);
            siliao.setShouxinren(rid);
            siliao.setBianhao(Info.getID());
            siliao.setAddtime(Info.getDateStr());
            DB.name(siliao).insert();
        }

        return JsonResult.success(siliao);
    }

    @RequestMapping("/sessionList")
    public ResponseData<List> chatSessionList(@RequestBody Map<String, Object> req)
    {
        // 获取会话列表
        JSONObject jsonObject = new JSONObject(req);
        String sid = jsonObject.getString("sid");
        String type = !StringUtil.isNullOrEmpty(jsonObject.getString("type")) ? jsonObject.getString("type") : "one";
        String lastdate = jsonObject.getString("lastdate");
        List<Map<String,Object>> list = new ArrayList();

        if("one".equals(type)){
            list = DB.name("Siliao").where("(faxinren = '"+sid+"' OR shouxinren='"+sid+"')").order("addtime desc").select();
        }else if("new".equals(type)){
            list = DB.name("Siliao")
                    .where("(faxinren = '"+sid+"' OR shouxinren='"+sid+"')")
                    .where("addtime",">" , lastdate)
                    .order("addtime asc")
                    .select();
        }

        List result = new ArrayList();
        if(list.size() > 0){
            for (Map<String,Object> map : list) {
                String u = String.valueOf(sid.equals(map.get("faxinren")) ? map.get("shouxinren") : map.get("faxinren"));
                Map user = getUser(u);
                if(user != null){
                    map.put("user" , user);
                    // 未读取数
                    long readCount = DB.name(Xiaoxi.class).where("siliaoid" , map.get("id"))
                            .where("fasongren" , "!=" , sid)
                            .where("shifouzhakan","否").count();

                    map.put("readCount" , readCount);
                    Xiaoxi last = DB.name(Xiaoxi.class).where("siliaoid" , map.get("id")).order("id desc").limit(1).find();
                    map.put("last",last);
                    result.add(map);
                }
            }
        }
        return JsonResult.success(result);
    }

    public static Map getUser(String u)
    {
        Map user = DB.name("admins").where("username" , u).find();
        if(user != null){
//            user.put("xingming" , user.get("nicheng"));
//            user.put("touxiang" , user.get("touxiang"));
            return user;
        }
        user = DB.name("wxuser").where("id" , u).find();
        if(user != null){
            user.put("xingming" , user.get("nickName"));
            user.put("touxiang" , user.get("avatarUrl"));
            return user;
        }


//        user = DB.name("admins").where("username" , u).find();
//        if(user != null){
//            user.put("xingming" , user.get("username"));
//            user.put("touxiang" , "/upload/1.png");
//            return user;
//        }
        return null;
    }


    @RequestMapping("/updateRead")
    // 更新为已读
    public ResponseData<Object> updateRead(@RequestBody Map<String, Object> req)
    {
        JSONObject jsonObject = new JSONObject(req);
        String chatid = jsonObject.getString("chatid");
        String sid = jsonObject.getString("sid");
        DB.name(Xiaoxi.class).where("siliaoid" , chatid).where("fasongren" , "!=" , sid).setField("shifouzhakan","是");
        //DB.name(Zaixiangoutong.class).where("id",chatid).setField("xiaoxizuihoushijian" , Info.getDateStr());
        return JsonResult.success("ok");
    }
    public static String getString(JSONObject obj , String name)
    {
        return getString(obj,name,"");
    }
    public static String getString(JSONObject obj , String name , String def)
    {
        if(StringUtil.isNullOrEmpty(obj.getString(name))){
            return def;
        }
        return obj.getString(name);
    }
    public static int getInt(JSONObject obj , String name)
    {
        return getInt(obj,name,0);
    }
    public static int getInt(JSONObject obj , String name , int def)
    {
        if(StringUtil.isNullOrEmpty(obj.getString(name))){
            return def;
        }
        return obj.getIntValue(name);
    }

    @RequestMapping("/chatMessage")
    public ResponseData<List> chatMessage(@RequestBody Map<String, Object> req)
    {
        JSONObject jsonObject = new JSONObject(req);
        String chatid = jsonObject.getString("chatid");
        int pageNumber = getInt(jsonObject,"pageNumber" , 1);
        int pageSize = getInt(jsonObject,"pageSize" , 20);
        String offsetMax = getString(jsonObject,"offsetMax" , "");
        String offsetMin = getString(jsonObject,"offsetMin" , "");
        String type = getString(jsonObject,"type");
        List list = new ArrayList();
        if(type.equals("one")){
            // 第一次加载
            list = DB.name(Xiaoxi.class).where("siliaoid",chatid).order("id desc").limit(pageSize).select();
        }else if(type.equals("top")){
            list = DB.name(Xiaoxi.class).where("siliaoid" , chatid)
                    .order("id desc").limit(pageSize)
                    .where("id" ,"<" , offsetMin).select();
        }else if(type.equals("new")){
            list = DB.name(Xiaoxi.class).where("siliaoid" , chatid)
                    .order("id desc").limit(pageSize)
                    .where("id" ,">" , offsetMax).select();
        }

        return JsonResult.success(list);
    }
}
